package com.sunnada.exam.service;

import com.alibaba.fastjson.JSON;
import com.sunnada.exam.dao.AnswerMapper;
import com.sunnada.exam.dao.QuestionMapper;
import com.sunnada.exam.dto.AnswerDto;
import com.sunnada.exam.dto.ResultTypeDto;
import com.sunnada.exam.enmu.ResultType;
import com.sunnada.exam.po.AnswerPo;
import com.sunnada.exam.po.QuestionPo;
import com.sunnada.exam.vo.QuestionVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionService {
    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    AnswerMapper answerMapper;
    @Autowired
    ResultsService resultsService;

    public List<QuestionVo> list(String tid){
        List<QuestionVo> result = new ArrayList<>();
        List<QuestionPo> qlist = questionMapper.list(tid);
        for (QuestionPo questionPo : qlist) {
            QuestionVo questionVo = new QuestionVo(questionPo);
            List<AnswerPo> alist = answerMapper.list(questionPo.getId());
            questionVo.setAnsSelect(alist);
            result.add(questionVo);
        }
        return result;
    }

    public ResultType check(AnswerDto ans){
        List<ResultTypeDto> type = new ArrayList<>();
        List<Integer> values = ans.getAnswer();
        type.add(new ResultTypeDto(ResultType.dominance,getSum(ResultType.dominance,values)));
        type.add(new ResultTypeDto(ResultType.extroversion,getSum(ResultType.extroversion,values)));
        type.add(new ResultTypeDto(ResultType.patience,getSum(ResultType.patience,values)));
        type.add(new ResultTypeDto(ResultType.precision,getSum(ResultType.precision,values)));
        type.add(new ResultTypeDto(ResultType.conformity,getSum(ResultType.conformity,values)));
        type.sort((o1, o2) -> o2.getResult()-o1.getResult());
        resultsService.insert(ans.getName(),JSON.toJSONString(type),1);
        return type.get(0).getResultType();
    }

    private Integer getSum(ResultType resultType,List<Integer> values){
        Integer result = 0;
        String[] arr = StringUtils.split(resultType.getContent(),",");
        for (String s : arr) {
            Integer i = Integer.parseInt(s);
            result += values.get(i-1);
        }
        return result;
    }
}


